package cn.mdmm.shiro;

import java.text.MessageFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.NamedFilterList;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.mdmm.service.system.SysMenuService;
import cn.modoumama.common.spring.SpringUtils;

public class ShiroUtils {
	private static Logger logger = LoggerFactory.getLogger(ShiroUtils.class);
	private static Date date = null;
	private static Map<String, NamedFilterList>  initFilterChains= null;
	/**
     * 默认premission字符串
     */
    public static final String PREMISSION_STRING = "perms[{0}]";
	
	private ShiroUtils(){}
	
	/** 
     * 重新载入过滤器url 
     * @param chains eg:keys:/static/**, value:authc,user,roles[admin] 
     */  
    public static void reloadShiroFilterChains(){
    	 try {
			SysMenuService sysMenuService = SpringUtils.getBean(SysMenuService.class);
			 Map<String, String> powers = sysMenuService.getAllPowers(date);
			 if(powers == null){
			 	return ;
			 }
			 powers.remove("");
			 powers.remove(null);
			DefaultFilterChainManager filterManager = getFilterChainManager();  
			synchronized (filterManager.getFilterChains()) {
				if(initFilterChains == null){
					initFilterChains = new LinkedHashMap<>();
					initFilterChains.putAll(filterManager.getFilterChains());
				}
			    filterManager.getFilterChains().clear();  
			    for(Entry<String,String> chain : powers.entrySet()){
			    	String powerValue = MessageFormat.format(PREMISSION_STRING, chain.getValue());
			        filterManager.createChain(chain.getKey(), powerValue);
			        logger.debug(chain.getKey() + " = " + powerValue);
			    }

			    filterManager.getFilterChains().putAll(initFilterChains);
			    date = new Date();
			    logger.debug("update shiro permission success...");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
    } 
    
    public static DefaultFilterChainManager getFilterChainManager() {  
        return ((DefaultFilterChainManager)((PathMatchingFilterChainResolver)SpringUtils.getBean(AbstractShiroFilter.class).getFilterChainResolver()).getFilterChainManager());  
    }
}
